package com.omesoft.hksnore.util.myactivity;

import android.app.Activity;
import android.app.Application;

import com.omesoft.hksnore.MainActivity;
import com.omesoft.hksnore.util.L;

import java.util.LinkedList;
import java.util.List;

/**
 * Activity堆栈管理。
 *
 * @author omesoft_lgc
 * @date 2016-3-2 上午11:53:47
 */
public class ActivityStack extends Application {
    private final static String TAG = "ActivityStack";

    // 运用list来保存们每一个activity是关键
    private List<Activity> mList = new LinkedList<Activity>();
    // 为了实现每次使用该类时不创建新的对象而创建的静态对象
    private static ActivityStack instance;

    // 构造方法
    private ActivityStack() {
    }

    // 实例化一次
    public synchronized static ActivityStack getInstance() {
        if (null == instance) {
            instance = new ActivityStack();
        }
        return instance;
    }

    // add Activity
    public void addActivity(Activity activity) {
        mList.add(activity);
    }

    // 关闭每一个list内的activity
    public void exit() {
        try {
            for (Activity activity : mList) {
                if (activity != null)
                    activity.finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.exit(0);
        }
    }

    /**
     * 退出指定的activity
     */
    public void popActivityByClass(Class<?>[] class1) {
        if (mList != null) {
            for (int i = 0; i < mList.size(); i++) {

                Activity activity = mList.get(i);
                for (Class<?> k : class1) {
                    L.v("lgc", "iii::" + i);
                    if (activity.getClass().equals(k)) {
                        L.v("lgc", "k::" + k.getName());
                        popActivity(activity);
                    } else {
                        L.v("lgc", "这个是：：" + activity.getClass().getName());
                    }
                }
            }
        }
    }

    // 退出栈顶Activity
    public void popActivity(Activity activity) {
        if (activity != null) {
            activity.finish();
            mList.remove(activity);
            // mActivityStack.pop();
            activity = null;
        }
    }

    /**
     * 退出所有activty 留下mainactivity
     */
    public void exitIsNotHaveMain() {
        try {
            for (Activity activity : mList) {
                if (!activity.getClass().equals(MainActivity.class))
                    activity.finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 杀进程
    public void onLowMemory() {
        super.onLowMemory();
        System.gc();
    }

}

